<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="550px"
    :before-close="handleClose"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-suffix="："
      label-width="110px"
    >
      <el-form-item label="应用方名称" prop="appName">
        <el-input
          v-model="form.appName"
          placeholder="请输入应用方名称"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleApplication">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addNewApplication, updateApplication } from "@/api/index";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    currentSelectApp: {
      type: Object,
      default: () => ({}),
    },
  },
  watch: {
    currentSelectApp: {
      handler(val) {
        if (val) {
          this.type = "update";
          this.title = "修改应用方";
          this.form.appName = val.appName;
        } else {
          this.type = "add";
          this.form.appName = "";
          this.title = "新增应用方";
        }
      },
    },
  },
  data() {
    return {
      type: "add",
      title: "",
      form: {
        appName: "",
      },
      rules: {
        appName: [
          { required: true, message: "请输入应用方名称", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleClose() {
      this.$refs.form.resetFields();
      this.$refs.form.clearValidate();
      this.$emit("update:visible", false);
    },
    handleApplication() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            appName: this.form.appName,
          };
          let fn = addNewApplication;
          if (this.type == "update") {
            params.appId = this.currentSelectApp.appId;
            fn = updateApplication;
          }
          fn(params).then((res) => {
            if (res.code == 200) {
              this.$message.success("新增应用方成功");
              this.$emit("confirm");
              this.handleClose();
            }
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style></style>
